!function ($) {
    $.extend({
        _jsonp: {
            scripts: {},
            counter: 1,
            charset: "gb2312",
            head: document.getElementsByTagName("head")[0],
            name: function (callback) {
                var name = "_jsonp_" + (new Date).getTime() + "_" + this.counter;
                this.counter++;
                var cb = function (json) {
                    eval("delete " + name),
                        callback(json),
                        $._jsonp.head.removeChild($._jsonp.scripts[name]),
                        delete $._jsonp.scripts[name]
                };
                return eval(name + " = cb"),
                    name
            },
            load: function (a, b) {
                var c = document.createElement("script");
                c.type = "text/javascript",
                    c.charset = this.charset,
                    c.src = a,
                    this.head.appendChild(c),
                    this.scripts[b] = c
            }
        },
        getJSONP: function (a, b) {
            var c = $._jsonp.name(b),
                a = a.replace(/{callback};/, c);
            return $._jsonp.load(a, c),
                this
        }
    })
}
(jQuery);
//-----------------------------------------------------------

//---------------------------------------------------------------
//c 省会

var iplocation=[];
var provinceCityJson = {};

//数据结构
/*
var iplocation = [
    {name: "北京", id: "1", c: 72},
    {name: "上海", id: "2", c: 78}
    ];

var provinceCityJson = {
    "p": iplocation,
    "1": [{"id": 72, "name": "朝阳区"}, {"id": 2800, "name": "海淀区"}],
    "2": [{"id": 2768, "name": "台湾市"}]
 };

 */

//根据省份ID获取名称
function getNameById(provinceId) {
    for (var i = 0; i < iplocation.length; i++) {
        if (iplocation[i].id == provinceId) {
            return iplocation[i].name;
        }
    }

    return "北京市";
}

function getAreaList(result) {
    var html = ["<ul class='area-list'>"];
    var longhtml = [];
    var longerhtml = [];
    if (result && result.length > 0) {
        for (var i = 0, j = result.length; i < j; i++) {
            result[i].name = result[i].name.replace(" ", "");
            if (result[i].name.length > 12) {
                longerhtml.push("<li class='longer-area'><a href='#none' data-value='" + result[i].id + "'>" + result[i].name + "</a></li>");
            }
            else if (result[i].name.length > 5) {
                longhtml.push("<li class='long-area'><a href='#none' data-value='" + result[i].id + "'>" + result[i].name + "</a></li>");
            }
            else {
                html.push("<li><a href='#none' data-value='" + result[i].id + "'>" + result[i].name + "</a></li>");
            }
        }
    }
    else {
        html.push("<li><a href='#none' data-value='" + currentAreaInfo.currentFid + "'> </a></li>");
    }
    html.push(longhtml.join(""));
    html.push(longerhtml.join(""));
    html.push("</ul>");

    return html.join("");
}

function cleanKuohao(str) {
    if (str && str.indexOf("(") > 0) {
        str = str.substring(0, str.indexOf("("));
    }
    if (str && str.indexOf("（") > 0) {
        str = str.substring(0, str.indexOf("（"));
    }
    return str;
}

function getCookie(name) {
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1)
        return null;
    var end = document.cookie.indexOf(';', len);
    if (end == -1)
        end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
}
(function ($) {
    $.fn.Address = function (cfg) {
        return this.each(function () {
            var JD_stock = $('<div class="content"><div data-widget="tabs" class="m JD-stock">'
                + '<div class="mt">'
                + '    <ul class="tab">'
                + '        <li data-index="0" data-widget="tab-item" class="curr"><a href="#none" class="hover"><em>请选择</em><i class="caret-b"></i></a></li>'
                + '        <li data-index="1" data-widget="tab-item" style="display:none;"><a href="#none" class=""><em>请选择</em><i class="caret-b"></i></a></li>'
                + '        <li data-index="2" data-widget="tab-item" style="display:none;"><a href="#none" class=""><em>请选择</em><i class="caret-b"></i></a></li>'
                + '        <li data-index="3" data-widget="tab-item" style="display:none;"><a href="#none" class=""><em>请选择</em><i class="caret-b"></i></a></li>'
                + '    </ul>'
                + '    <div class="stock-line"></div>'
                + '</div>'
                + '<div class="mc stock_province_item" data-area="0" data-widget="tab-content"></div>'
                + '<div class="mc stock_city_item" data-area="1" data-widget="tab-content"></div>'
                + '<div class="mc stock_area_item" data-area="2" data-widget="tab-content"></div>'
                + '<div class="mc stock_town_item" data-area="3" data-widget="tab-content"></div>'
                + '</div></div>');
            var ul = $(this),
                store_selector = ul.find('div.store-selector'),
                addrIDContainer = ul.find('div.addrID'); //ID容器

            var currentAreaInfo; //保存当前信息变量
            function getStockOpt(id, name) {

                areaTabContainer.eq(currentAreaInfo.currentLevel-1).addClass('curr').find("em").html(name);
                areaTabContainer.eq(currentAreaInfo.currentLevel).hide();
                if(currentAreaInfo.currentLevel==1){
                    areaTabContainer.eq(currentAreaInfo.currentLevel+1).hide();
                }

                if (currentAreaInfo.currentLevel == 3) {

                    currentAreaInfo.currentAreaId = id;
                    currentAreaInfo.currentAreaName = name;
                    if (!page_load) {
                        currentAreaInfo.currentTownId = 0;
                        currentAreaInfo.currentTownName = "";
                    }
                }
                else if (currentAreaInfo.currentLevel == 4) {
                    currentAreaInfo.currentTownId = id;
                    currentAreaInfo.currentTownName = name;
                }
                store_selector.removeClass('hover');
                if (page_load) {
                    page_load = false;
                }

                //替换gSC
                //只选择最低级地名-显示完整地区名--------------------------------------------------------------------
                //最后的获取结果为所选的最后一级地名，比如若只选到县名，则保留县名，同理市名，省名。
                var address = currentAreaInfo.currentProvinceName + currentAreaInfo.currentCityName + currentAreaInfo.currentAreaName + currentAreaInfo.currentTownName;
                var ids=[currentAreaInfo.currentProvinceId,currentAreaInfo.currentCityId,currentAreaInfo.currentAreaId];

                //只选择最低级地名--------------------------------------------------------------------	
                //最后的获取结果为所选的最后一级地名，比如若只选到县名，则保留县名，同理市名，省名。
                var tTown = "", tArea = "", tCity = "", tProvince = "";
                var tID = "";
                tProvince = currentAreaInfo.currentProvinceName;
                tCity = cleanKuohao(currentAreaInfo.currentCityName);
                tArea = cleanKuohao(currentAreaInfo.currentAreaName);
                tTown = cleanKuohao(currentAreaInfo.currentTownName);
                //tID=currentAreaInfo.currentAreaId;

                if (tTown != "") {
                    tProvince = tCity = tArea = "";
                    tID = currentAreaInfo.currentTownId;
                }
                else if (tArea != "") {
                    tProvince = tCity = "";
                    tID = currentAreaInfo.currentAreaId;
                }
                else if (tCity != "") {
                    tProvince = "";
                    tID = currentAreaInfo.currentCityId;
                }
                else {
                    tID = currentAreaInfo.currentProvinceId;
                }
                var oldAddrHtml = store_selector.find(".text div").text();
                var oldAddrID = store_selector.find(".text div").attr("title");
                var addrHtml = "";
                var addrID = "";
                if (oldAddrHtml != "") {
                    addrHtml = oldAddrHtml + "," + tProvince + tCity + tArea + tTown;
                    addrID = oldAddrID + "," + tID;
                }
                else {
                    addrHtml = tProvince + tCity + tArea + tTown;
                    addrID = tID;
                }

                store_selector.find(".text div").html(tTown||tArea||tCity||tProvince);
                store_selector.find(".store-input").val(ids).trigger('input');tools.log(ids);
            }

            function chooseProvince(provinceId) {
                currentAreaInfo.currentLevel = 1;
                currentAreaInfo.currentProvinceId = provinceId;
                currentAreaInfo.currentProvinceName = getNameById(provinceId);
                if (!page_load) {
                    currentAreaInfo.currentCityId = 0;
                    currentAreaInfo.currentCityName = "";
                    currentAreaInfo.currentAreaId = 0;
                    currentAreaInfo.currentAreaName = "";
                    currentAreaInfo.currentTownId = 0;
                    currentAreaInfo.currentTownName = "";
                }
                areaTabContainer.eq(0).find("em").html(currentAreaInfo.currentProvinceName);

                //tools.log('选择的provinceId:',provinceId,provinceCityJson["" + provinceId]);
                if (provinceCityJson["" + provinceId]&&provinceCityJson["" + provinceId].length) {
                    provinceContainer.hide();
                    areaTabContainer.eq(0).removeClass("curr");
                    areaTabContainer.eq(1).addClass("curr").show().find("em").html("请选择");
                    areaTabContainer.eq(2).hide();
                    areaTabContainer.eq(3).hide();
                    cityContainer.show();
                    areaContainer.hide();
                    townaContainer.hide();

                    cityContainer.html(getAreaList(provinceCityJson["" + provinceId]));
                    cityContainer.find("a").on('click', function () {
                        if (page_load) {
                            page_load = false;
                        }
                        store_selector.unbind("mouseout");
                        chooseCity($(this).attr("data-value"), $(this).html());
                    });
                    if (page_load) { //省初始化加载
                        if (currentAreaInfo.currentCityId && new Number(currentAreaInfo.currentCityId) > 0) {
                            chooseCity(currentAreaInfo.currentCityId, cityContainer.find("a[data-value='" + currentAreaInfo.currentCityId + "']").html());
                        }
                        else {
                            chooseCity(cityContainer.find("a").eq(0).attr("data-value"), cityContainer.find("a").eq(0).html());
                        }
                    }
                }else{
                    getStockOpt(provinceId, currentAreaInfo.currentProvinceName);
                }
            }

            function chooseCity(cityId, cityName) {
                provinceContainer.hide();

                currentAreaInfo.currentLevel = 2;
                currentAreaInfo.currentCityId = cityId;
                currentAreaInfo.currentCityName = cityName;
                if (!page_load) {
                    currentAreaInfo.currentAreaId = 0;
                    currentAreaInfo.currentAreaName = "";
                    currentAreaInfo.currentTownId = 0;
                    currentAreaInfo.currentTownName = "";
                }
                areaTabContainer.eq(1).removeClass("curr").find("em").html(cityName);


                if (provinceCityJson["" + cityId]&&provinceCityJson["" + cityId].length) {
                    cityContainer.hide();
                    areaTabContainer.eq(2).addClass("curr").show().find("em").html("请选择");
                    areaTabContainer.eq(3).hide();
                    areaContainer.show().html("<div class='iloading'>正在加载中，请稍候...</div>");
                    townaContainer.hide();
                    currentDom = areaContainer;

                    currentDom.html(getAreaList(provinceCityJson["" + cityId]));
                    if (currentAreaInfo.currentLevel >= 2) {
                        currentDom.find("a").on('click',function () {
                            if (page_load) {
                                page_load = false;
                            }
                            if (currentDom.hasClass("stock_area_item")) {
                                currentAreaInfo.currentLevel = 3;
                            }
                            else if (currentDom.hasClass("stock_town_item")) {
                                currentAreaInfo.currentLevel = 4;
                            }
                            getStockOpt($(this).attr("data-value"), $(this).html());
                        });


                        if (page_load) { //初始化加载
                            currentAreaInfo.currentLevel = currentAreaInfo.currentLevel == 2 ? 3 : 4;
                            if (currentAreaInfo.currentAreaId) {
                                areaTabContainer.eq(2).find("em").html(currentDom.find('[data-value="'+currentAreaInfo.currentAreaId+'"]').text());
                                getStockOpt(currentAreaInfo.currentAreaId, currentDom.find('[data-value="'+currentAreaInfo.currentAreaId+'"]').text());
                            }
                            else {
                                getStockOpt(currentDom.find("a").eq(0).attr("data-value"), currentDom.find("a").eq(0).html());
                            }
                        }
                    }
                } else {
                    getStockOpt(cityId, cityName);
                }
            }

            store_selector.find('.text').after(JD_stock);
            var areaTabContainer = JD_stock.find(".tab li");
            var provinceContainer = ul.find("div.stock_province_item");
            var cityContainer = ul.find("div.stock_city_item");
            var areaContainer = ul.find("div.stock_area_item");
            var townaContainer = ul.find("div.stock_town_item");
            var currentDom = provinceContainer;

            //当前地域信息
            //初始化当前地域信息
            function CurrentAreaInfoInit(proid, cityid, areaid, townid) {
                currentAreaInfo = {
                    "currentLevel": 1,
                    "currentProvinceId": 1,
                    "currentProvinceName": "北京市",
                    "currentCityId": 0,
                    "currentCityName": "",
                    "currentAreaId": 0,
                    "currentAreaName": "",
                    "currentTownId": 0,
                    "currentTownName": ""
                };
                var ipLoc = getCookie("ipLoc-djd");
                ipLoc = ipLoc ? ipLoc.split("-") : [proid || 1, cityid || 72, areaid || 0, townid || 0];
                if (ipLoc.length > 0 && ipLoc[0]) {
                    currentAreaInfo.currentProvinceId = ipLoc[0];
                    currentAreaInfo.currentProvinceName = getNameById(ipLoc[0]);
                }
                if (ipLoc.length > 1 && ipLoc[1]) {
                    currentAreaInfo.currentCityId = ipLoc[1];
                }
                if (ipLoc.length > 2 && ipLoc[2]) {
                    currentAreaInfo.currentAreaId = ipLoc[2];
                }
                if (ipLoc.length > 3 && ipLoc[3]) {
                    currentAreaInfo.currentTownId = ipLoc[3];
                }
                provinceContainer.html(getAreaList(provinceCityJson.p));
                chooseProvince(currentAreaInfo.currentProvinceId); //加载省，需要一级一级加载，不能越级
            }

            var page_load = true;

            store_selector.unbind("mouseover").bind("mouseover", function () {
                //tools.log('mouseover');
                store_selector.addClass('hover');
                store_selector.find('.content').show();
                JD_stock.show();

            }).find("dl").remove();

            //隐藏事件
            store_selector.unbind("mouseout").bind("mouseout", function () {
                store_selector.removeClass('hover');
                store_selector.find('.content').hide();
                JD_stock.hide();
            });


            CurrentAreaInfoInit(cfg.proid, cfg.cityid, cfg.areaid, cfg.townid);

            //当第0个选项卡被点击时，显示“省”选项面板
            areaTabContainer.eq(0).find("a").click(function () {
                areaTabContainer.removeClass("curr");
                areaTabContainer.eq(0).addClass("curr").show();
                provinceContainer.show();
                cityContainer.hide();
                areaContainer.hide();
                townaContainer.hide();
                //areaTabContainer.eq(1).hide();
                //areaTabContainer.eq(2).hide();
                //areaTabContainer.eq(3).hide();
            });

            //当第1个选项卡被点击时，显示“市”选项面板
            areaTabContainer.eq(1).find("a").click(function () {
                areaTabContainer.removeClass("curr");
                areaTabContainer.eq(1).addClass("curr").show();
                provinceContainer.hide();
                cityContainer.show();
                areaContainer.hide();
                townaContainer.hide();
                //areaTabContainer.eq(2).hide();
                //areaTabContainer.eq(3).hide();
            });

            //当第2个选项卡被点击时，显示“县”选项面板
            areaTabContainer.eq(2).find("a").click(function () {
                areaTabContainer.removeClass("curr");
                areaTabContainer.eq(2).addClass("curr").show();
                provinceContainer.hide();
                cityContainer.hide();
                areaContainer.show();
                townaContainer.hide();
                //areaTabContainer.eq(3).hide();
            });

            provinceContainer.find("a").on('click',function () {
                if (page_load) {
                    page_load = false;
                }
                store_selector.unbind("mouseout");
                chooseProvince($(this).attr("data-value"));
            }).end();

        });
    };
})(jQuery);